package com.ruoyi.vplat.websocket.handler;

import java.util.Date;
import java.util.HashMap;

import javax.websocket.Session;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter.Feature;
import com.ruoyi.common.event.NetworkEvent;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.websocket.handler.AbstractWebsocketMsgHandler;
import com.ruoyi.common.websocket.server.WebSocketUtils;
import com.ruoyi.common.websocket.server.WebsocketServer;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class WebsocketMsgHandler3006 extends AbstractWebsocketMsgHandler {
	@Autowired
	private ApplicationEventPublisher eventPublisher;
	@Override
	public void invoke(JSONObject message) {
		JSONObject command = message.getJSONObject("command");
		JSONObject param = message.getJSONObject("param");
		String terminateId = param.getString("terminateId");
		String clientType = command.getString("iProtocol");
		String clientId = command.getString("szClientId");
		int seqNum = command.getIntValue("iSeqNum");
		String datetime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		JSONObject res = getCommandTemplate("3007",new HashMap<String, Object>(){{
			put("protocol", clientType);
			put("seqNum", seqNum);
			put("clientId", clientId);
			put("datetime", datetime);
		}});
		//log.warn(message.toJSONString());
		WebSocketUtils.sendMessage(clientId, res);
		Session session = WebSocketUtils.getSession(clientId);
		WebsocketServer websocketServer = SpringUtils.getBean(WebsocketServer.class);
		websocketServer.update(session);
		if(clientType.equals("10000")) {//云边协同客户端
			String text = JSON.toJSONString(message,Feature.WriteMapNullValue);
			eventPublisher.publishEvent(new NetworkEvent(this, text));
		}
	}
}
